
import {Product} from '../../pages/product/product-model.js';
import {Cart} from '../../pages/cart/cart-model.js';

var product = new Product();
var cart = new Cart();

Page({
  data: {
    productCount:1,
    countsArray:[1,2,3,4,5,6,7,8,9,10],
    tabs:[
      '商品详情',
      '产品参数',
      '售后保障',
    ],
    currentTabIndex:0
  },
  onLoad: function (options) {
    var id = options.id;
    var name = options.name;
    this.data.id = id;
    this.data.name = name;
    this._loadData();
  },
  onReady:function(){
    wx.setNavigationBarTitle({
      title: this.data.name,
    })
  },
  _loadData:function(){
    product.getProductData(this.data.id,(data)=>{
      this.setData({
        cartTotalCounts: cart.getCartTotalCounts(),
        product:data
      });
    });
  },
  bindPickerChange:function(event){
    var index = event.detail.value;
    var count = this.data.countsArray[index];
    this.setData({
      productCount: count,
    });
  },
  onTabsItemTap:function(event){
    var index = product.getDataSet(event,'index');
    this.setData({
      currentTabIndex:index
    });
  },
  // 添加商品至购物车
  addToCart:function() {
    var tempObj = {};
    var keys = ['id', 'name','main_img_url','price'];
    for (var key in this.data.product){
      if(keys.indexOf(key)>=0){
        tempObj[key] = this.data.product[key];
      }
    }
    cart.add(tempObj,this.data.productCount);
    this.setData({
      cartTotalCounts: this.data.cartTotalCounts += this.data.productCount,
    });
  },
  // 购物车页面跳转
  onCartTap:function(){
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  }
})